<template>
	<div class="table-box">
		<ProTable ref="proTable" title="管理" :columns="columns" :requestApi="getsysuserList" selectId="userId">
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openDrawer(1)" v-if="isAuth('generator:sysuser:add')"
					>新增</el-button
				>
				<el-button
					type="danger"
					:icon="Delete"
					plain
					@click="batchDelete(scope.selectedListIds as unknown as number[])"
					:disabled="!scope.isSelected"
					v-if="isAuth('generator:sysuser:delete')"
				>
					批量删除
				</el-button>
			</template>
			<!-- status -->
			<template #status="scope">
				<el-link :type="scope.row.status === 1 ? 'success' : 'danger'" :underline="false">{{
					scope.row.status === 1 ? '正常' : '异常'
				}}</el-link>
			</template>

			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="EditPen" @click="openDrawer(2, scope.row)" v-if="isAuth('generator:sysuser:update')"
					>编辑</el-button
				>
				<el-button type="danger" link :icon="Delete" @click="deleteAccount(scope.row)" v-if="isAuth('generator:sysuser:delete')"
					>删除</el-button
				>
			</template>
		</ProTable>
		<!-- 新增和编辑 -->
		<zhy-pop-form :drawerTitle="drawerTitle" ref="popRef">
			<template #formbox>
				<form-box :itemForm="itemForm" :submitting="submitting" :closeForm="cancelForm" :submit-form="submitForm" ref="formbox">
				</form-box> </template
		></zhy-pop-form>
	</div>
</template>

<script setup lang="tsx" name="sysuser">
import { ref, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { ZhyPopForm, ProTable, FormBox } from '@/components';
import { useCheckout, useFilterHandle } from '@/hooks';
import { FromBoxProps } from '@/components/FormBox/interface';
import { ColumnProps } from '@/components/ProTable/interface';
import { useHandleData } from '@/hooks/useHandleData';
import { CirclePlus, Delete, EditPen } from '@element-plus/icons-vue';
import { getsysuserList, editsysuser, addsysuser, deletesysuserBatch } from '@/api/modules/sysuser';
import { isAuth } from '@/utils/util';
const { checkPhone, getValidRule } = useCheckout();
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 表格配置项
const columns: ColumnProps[] = [
	{ type: 'selection', fixed: 'left' },
	{ prop: 'userId', label: '' },
	{ prop: 'username', label: '用户名' },
	{ prop: 'password', label: '密码' },
	{ prop: 'salt', label: '盐' },
	{ prop: 'email', label: '邮箱' },
	{ prop: 'mobile', label: '手机号' },
	{ prop: 'status', label: '状态  0：禁用   1：正常' },
	{ prop: 'createUserId', label: '创建者ID' },
	{
		prop: 'createTime',
		label: '创建时间',
		search: {
			el: 'date-picker',
			keyName: ['startDate', 'endDate'],
			props: { type: 'datetimerange', 'value-format': 'YYYY-MM-DD HH:mm:ss', clearable: true }
		}
	},
	{ prop: 'userLogo', label: '用户登录图标' },
	{
		prop: 'operation',
		label: '操作',
		fixed: 'right'
	}
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	await useHandleData(deletesysuserBatch, [params?.userId], `删除【${params.username}】`);
	proTable.value.getTableList();
};

// 批量删除(表格组件需要设置selectId)
const batchDelete = async (id: number[]) => {
	await useHandleData(deletesysuserBatch, id, `删除${id.length}条数据`);
	// 清除表格复选框之前选中状态
	proTable.value.clearSelection();
	// 刷新数据
	proTable.value.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const popRef = ref<InstanceType<typeof ZhyPopForm>>();
const formbox = ref<InstanceType<typeof FormBox>>();
const popRef2 = ref<InstanceType<typeof ZhyPopForm>>();

const handleType = ref(1);
const drawerTitle = ref<string>('新增');

const openDrawer = async (type: number, row?: any) => {
	popRef.value!.visible = true;
	handleType.value = type;
	drawerTitle.value = type === 1 ? '新增' : '编辑';

	// 编辑
	if (type === 2) {
		nextTick(() => {
			formbox.value!.formParam = Object.assign(formbox.value!.formParam, {
				...row
			});
		});
	}
};

// 提交表单
const submitting = ref(false);

const submitForm = (): void => {
	const params: any = formbox.value!.formParam;

	submitting.value = true;
	// 新增
	if (handleType.value === 1) {
		saveM(params);
	} else {
		// 编辑
		updateM(params);
	}
};

// 取消
const cancelForm = () => {
	popRef.value!.visible = false;
	popRef2.value!.visible = false;
};

const updateM = (params: any): void => {
	editsysuser({
		...params,
		status: params.status ? 1 : 0
	})
		.then(() => {
			ElMessage.success('修改成功');
			submitting.value = false;
			popRef.value!.visible = false;
			proTable.value.getTableList();
		})
		.catch(() => {
			submitting.value = false;
		});
};
const saveM = (params: any): void => {
	addsysuser(params)
		.then(() => {
			ElMessage.success('新增成功');
			submitting.value = false;
			popRef.value!.visible = false;
			proTable.value.getTableList();
		})
		.catch(() => {
			submitting.value = false;
		});
};
const itemForm = computed(() => {
	const itemForm: FromBoxProps[] = [
		// prop 目前不用type字段，会有冲突

		{
			prop: 'username',
			label: '用户名',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '用户名' })
		},
		{
			prop: 'password',
			label: '密码',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '密码' })
		},
		{
			prop: 'salt',
			label: '盐',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '盐' })
		},
		{
			prop: 'email',
			label: '邮箱',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '邮箱' })
		},
		{
			prop: 'mobile',
			label: '手机号',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '手机号' })
		},
		{
			prop: 'status',
			label: '状态  0：禁用   1：正常',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '状态  0：禁用   1：正常' })
		},
		{
			prop: 'createUserId',
			label: '创建者ID',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '创建者ID' })
		},
		{
			prop: 'createTime',
			label: '创建时间',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '创建时间' })
		},
		{
			prop: 'userLogo',
			label: '用户登录图标',
			form: { el: 'input', props: { maxlength: 50 } },
			rules: getValidRule({ message: '用户登录图标' })
		}
	];
	return itemForm;
});
</script>
